package me.mcxiafeng.Event;

import java.util.ArrayList;
import java.util.Random;

import org.bukkit.Bukkit;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import me.mcxiafeng.Main;
import me.mcxiafeng.GUI.GuiClickGift;
import me.mcxiafeng.Util.SkullItem;

public class ClickGiftEvent implements Listener{
	
	@EventHandler
	private void OnClickBlock(PlayerInteractEvent event) {
		Player player = event.getPlayer();
		if(event.getItem() != null && event.getItem().getItemMeta() != null && event.getItem().getItemMeta().getDisplayName().contains("§5七夕礼物")) {
			ArrayList<String> list = (ArrayList<String>) Main.instease.getConfig().getList("prize");
			String line = list.get(new Random().nextInt(list.size()));
			if(line.contains("TNT")) {
				player.sendMessage("§c恭喜你抽中了TNT雨");
				player.getWorld().spawnEntity(player.getLocation().clone().add(0, 5, 0), EntityType.PRIMED_TNT);
				player.getWorld().spawnEntity(player.getLocation().clone().add(1, 5, 0), EntityType.PRIMED_TNT);
				player.getWorld().spawnEntity(player.getLocation().clone().add(0, 5, 1), EntityType.PRIMED_TNT);
				player.getWorld().spawnEntity(player.getLocation().clone().add(1, 5, 1), EntityType.PRIMED_TNT);
			}
			else if(line.contains("[command]")) {
				String cmd = line.substring(line.indexOf(":")+1).replace("[name]", player.getName());
				line = line.split(" ")[1];
				String msg = line.substring(0,line.indexOf(":")).replace("&", "§");
				player.sendMessage(msg);
				Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd);
			}
			if(event.getItem().getAmount() > 1) {
				event.getItem().setAmount(event.getItem().getAmount()-1);
			}
			else {
				event.getPlayer().getInventory().remove(event.getItem());
			}
			event.setCancelled(true);
			
		}
	}
	
	@EventHandler
	private void onClickInv(InventoryClickEvent event) {
		if(event.getInventory().getName().contains("§a礼物选取")) {
			if(event.getCurrentItem() != null && event.getCurrentItem().getItemMeta() != null && event.getCurrentItem().getItemMeta().getDisplayName().contains("§aGift ")) {
				ItemStack is = SkullItem.createSkull(GuiClickGift.giftmap.get(Integer.valueOf(event.getCurrentItem().getItemMeta().getDisplayName().split(" ")[1])));
				ItemMeta im = is.getItemMeta();
				im.setDisplayName("§5七夕礼物");
				is.setItemMeta(im);
				event.getWhoClicked().getInventory().addItem(is);
			}
			event.setCancelled(true);
		}
	}

}
